package com.ltx.bugseeker.exception;

import com.ltx.bugseeker.common.Result;
import com.ltx.bugseeker.common.ResultCode;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 * 统一处理系统中的各种异常，返回标准的错误响应格式
 * 
 * @author ltx
 * @since 2025-10-20 14:43:42
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    /**
     * 处理业务异常
     * 
     * @param e 业务异常
     * @param request HTTP请求对象
     * @return 统一错误响应
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<Void> handleBusinessException(BusinessException e, HttpServletRequest request) {
        log.warn("业务异常: {} - {}, 请求路径: {}", e.getCode(), e.getMessage(), request.getRequestURI());
        return Result.error(e.getCode(), e.getMessage());
    }
    
    /**
     * 处理参数校验异常 - @Valid注解校验失败
     * 
     * @param e 方法参数校验异常
     * @param request HTTP请求对象
     * @return 统一错误响应
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<List<String>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
        List<String> errors = e.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.toList());
        
        log.warn("参数校验异常: {}, 请求路径: {}", errors, request.getRequestURI());
        return Result.error(ResultCode.BAD_REQUEST.getCode(), "参数校验失败", errors);
    }
    
    /**
     * 处理参数绑定异常 - @Validated注解校验失败
     * 
     * @param e 参数绑定异常
     * @param request HTTP请求对象
     * @return 统一错误响应
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<List<String>> handleBindException(BindException e, HttpServletRequest request) {
        List<String> errors = e.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.toList());
        
        log.warn("参数绑定异常: {}, 请求路径: {}", errors, request.getRequestURI());
        return Result.error(ResultCode.BAD_REQUEST.getCode(), "参数绑定失败", errors);
    }
    
    /**
     * 处理参数类型不匹配异常
     * 
     * @param e 参数类型不匹配异常
     * @param request HTTP请求对象
     * @return 统一错误响应
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
        String message = String.format("参数类型错误: %s 应该是 %s 类型", 
                e.getName(), 
                e.getRequiredType() != null ? e.getRequiredType().getSimpleName() : "未知");
        
        log.warn("参数类型不匹配异常: {}, 请求路径: {}", message, request.getRequestURI());
        return Result.error(ResultCode.BAD_REQUEST.getCode(), message);
    }
    
    /**
     * 处理非法参数异常
     * 
     * @param e 非法参数异常
     * @param request HTTP请求对象
     * @return 统一错误响应
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleIllegalArgumentException(IllegalArgumentException e, HttpServletRequest request) {
        log.warn("非法参数异常: {}, 请求路径: {}", e.getMessage(), request.getRequestURI());
        return Result.error(ResultCode.BAD_REQUEST.getCode(), e.getMessage());
    }
    
    /**
     * 处理空指针异常
     * 
     * @param e 空指针异常
     * @param request HTTP请求对象
     * @return 统一错误响应
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Void> handleNullPointerException(NullPointerException e, HttpServletRequest request) {
        log.error("空指针异常, 请求路径: {}", request.getRequestURI(), e);
        return Result.error(ResultCode.INTERNAL_SERVER_ERROR);
    }
    
    /**
     * 处理运行时异常
     * 
     * @param e 运行时异常
     * @param request HTTP请求对象
     * @return 统一错误响应
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Void> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        log.error("运行时异常, 请求路径: {}", request.getRequestURI(), e);
        return Result.error(ResultCode.INTERNAL_SERVER_ERROR);
    }
    
    /**
     * 处理其他未知异常
     * 
     * @param e 异常
     * @param request HTTP请求对象
     * @return 统一错误响应
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Void> handleException(Exception e, HttpServletRequest request) {
        log.error("未知异常, 请求路径: {}", request.getRequestURI(), e);
        return Result.error(ResultCode.INTERNAL_SERVER_ERROR);
    }
}